package com.huiyun.project.im.server.biz.controller.sv;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huiyun.project.common.core.domain.R;
import com.huiyun.project.common.core.util.fn.FunctionUtils;
import com.huiyun.project.common.sequence.IdUtils;
import com.huiyun.project.im.consts.ImCsSessionConst;
import com.huiyun.project.im.core.service.IImSessionConfigService;
import com.huiyun.project.im.core.service.IImCsSessionService;
import com.huiyun.project.im.core.service.IImTenantService;
import com.huiyun.project.im.core.service.IImUserService;
import com.huiyun.project.im.entity.ImCsSession;
import com.huiyun.project.im.entity.ImCsSessionConfig;
import com.huiyun.project.im.entity.ImTenant;
import com.huiyun.project.im.entity.ImUser;
import org.jim.core.ImConst;
import org.jim.core.packets.cs.session.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.wf.jwtp.annotation.Inner;

import java.util.*;

@RestController
@RequestMapping("sv/cs/session")
public class ImCsSessionController {
    @Autowired
    private IImCsSessionService sessionService;
    @Autowired
    private IImUserService imUserService;
    @Autowired
    private IImTenantService imTenantService;
    @Autowired
    private IImSessionConfigService sessionConfigService;


    //查询有效会话列表
    @GetMapping("/getSessionList")
    @Inner
    public R<List<JimCsGetSessionResp>> getSessionList(JimCsGetSessionReq jimGetSessionReq) {
        return FunctionUtils.wrapper(() -> {
            List<JimCsGetSessionResp> respList = new ArrayList<>();
            if (ImConst.CS_OPERATE.equals(jimGetSessionReq.getOperateType())) {
                //客服操作
                //查询该客服有效会话
                Page<ImCsSession> sessionPage = sessionService.page(new Page(jimGetSessionReq.getPageNum(), jimGetSessionReq.getPageSize()), Wrappers.<ImCsSession>lambdaQuery()
                        .eq(ImCsSession::getCsId, jimGetSessionReq.getUid())
                        .eq(ImCsSession::getStatus, ImCsSessionConst.STATUS.INSERVICE.getValue())
                        .orderByDesc(ImCsSession::getBeginTime)
                );
                if (CollectionUtil.isNotEmpty(sessionPage.getRecords())) {
                    JimCsGetSessionResp resp;
                    for (ImCsSession imSession : sessionPage.getRecords()) {
                        resp = new JimCsGetSessionResp();
                        BeanUtil.copyProperties(imSession, resp);
                        resp.setSessionId(imSession.getId());
                        resp.setUnReadNum(imSession.getCsUnreadNum());
                        respList.add(resp);
                    }
                }

            } else if (ImConst.USER_OPERATE.equals(jimGetSessionReq.getOperateType())) {
                //客户操作
                //查询所有会话 按租户分组 去重复
//                Condition map = new Condition();
//                Page<ImCsSession> csSessionDtoPage = sessionService.getCustomSessionList(new Page(jimGetSessionReq.getPageNum(), jimGetSessionReq.getPageNum()), map);
//                if (CollectionUtil.isNotEmpty(csSessionDtoPage.getRecords())) {
//                    JimCsGetSessionResp resp;
//                    for (ImCsSession imSession : csSessionDtoPage.getRecords()) {
//                        resp = new JimCsGetSessionResp();
//                        BeanUtil.copyProperties(imSession, resp);
//                        resp.setSessionId(imSession.getId());
//                        resp.setUnReadNum(imSession.getUserUnreadNum());
//                        respList.add(resp);
//                    }
//                }
            }
            return R.ok(respList);
        });
    }

    //根据id查询有效会话
    @GetMapping("/getSessionById")
    @Inner
    public R<JimCsGetSessionResp> getSessionById(String sessionId) {
        return FunctionUtils.wrapper(() -> {
            JimCsGetSessionResp resp = new JimCsGetSessionResp();
            ImCsSession imSession = sessionService.getOne(Wrappers.<ImCsSession>lambdaQuery()
                    .eq(ImCsSession::getId, sessionId)
                    .eq(ImCsSession::getStatus, ImCsSessionConst.STATUS.INSERVICE.getValue())//在线的
                    .orderByDesc(ImCsSession::getBeginTime)
            );
            Assert.notNull(imSession);
            BeanUtil.copyProperties(imSession, resp);
            resp.setSessionId(imSession.getId());
            ImTenant tenant = imTenantService.getById(imSession.getCsTenantId());
            resp.setCsTenantName(tenant.getName());
            resp.setCsTenantLogo(tenant.getLogo());
            return R.ok(resp);
        });
    }

    /**
     * 创建会话session
     * @param sessionReq
     * @return
     */
    @PostMapping("/createSession")
    @Inner
    public R<JimCsSession> createSession(@Validated @RequestBody JimCsCreateSessionReq sessionReq) {
        return FunctionUtils.wrapper(() -> {
            ImUser cs = imUserService.getById(sessionReq.getCsId());
            ImUser user = imUserService.getById(sessionReq.getUserId());
            Date now = new Date();
            ImCsSession imSession = new ImCsSession();
            imSession.setId(String.valueOf(IdUtils.getId()));
            imSession.setStatus(ImCsSessionConst.STATUS.INSERVICE.getValue());
            imSession.setIpAddr(sessionReq.getIp());
            imSession.setAppKey(sessionReq.getAppKey());
            imSession.setBeginTime(now);
            imSession.setCsOrgId(sessionReq.getCsOrgId());
            imSession.setCsTenantId(sessionReq.getCsTenantId());
            imSession.setCsId(sessionReq.getCsId());
            imSession.setCsSpId(cs.getImSpId());
            imSession.setCsNick(cs.getNick());
            imSession.setUserId(sessionReq.getUserId());
            imSession.setUserNick(user.getNick());
            imSession.setUserSource(sessionReq.getUserSource());
            imSession.setDevice(sessionReq.getDevice());
            imSession.setDevicePlatform(sessionReq.getDevicePlatform());
            imSession.setSort(1l);
            sessionService.save(imSession);
            JimCsSession resp = new JimCsSession();
            BeanUtil.copyProperties(imSession, resp);
            //设置租户信息
            ImTenant tenant = imTenantService.getById(imSession.getCsTenantId());
            resp.setCsTenantCate(tenant.getTenantCate());
            resp.setCsTenantName(tenant.getName());
            resp.setCsTenantLogo(tenant.getLogo());
            return R.ok(resp);
        });
    }


    @GetMapping("/getConfig")
    @Inner(value = false)
    public R<JimCsSessionConfigResp> getConfig(@RequestParam("tenantId") String tenantId) {
        return FunctionUtils.wrapper(() -> {
            ImCsSessionConfig imSessionConfig = sessionConfigService.getByTenantId(tenantId);
            JimCsSessionConfigResp jimSessionConfig = new JimCsSessionConfigResp();
            BeanUtil.copyProperties(imSessionConfig, jimSessionConfig);
            return R.ok(jimSessionConfig);
        });
    }

    /**
     * 获取所有企业租户配置
     *
     * @return
     */
    @GetMapping("/getCsConfig")
    @Inner(value = false)
    public R<List<JimCsSessionConfigResp>> getCsConfig() {
        return FunctionUtils.wrapper(() -> {
          List<JimCsSessionConfigResp> list=new ArrayList<>();
            List<ImCsSessionConfig> configList = sessionConfigService.list();
            if (CollectionUtil.isNotEmpty(configList)) {
                JimCsSessionConfigResp resp;
                for (ImCsSessionConfig config : configList) {
                    resp = new JimCsSessionConfigResp();
                    BeanUtil.copyProperties(config, resp);
                    list.add(resp);
                }
            }
            return R.ok(list);
        });
    }

    @GetMapping("/csEnd")
    @Inner
    public R<JimCsSessionConfigResp> csEnd(@RequestParam("tenantId") String tenantId) {
        return FunctionUtils.wrapper(() -> {
            ImCsSessionConfig imSessionConfig = sessionConfigService.getByTenantId(tenantId);
            JimCsSessionConfigResp jimSessionConfig = new JimCsSessionConfigResp();
            BeanUtil.copyProperties(imSessionConfig, jimSessionConfig);
            return R.ok(jimSessionConfig);
        });
    }


}
